package com.kcht.itsed.mws.subscribescheduler.biz;

import com.kcht.itsed.mws.alemodel.ECReports;
import com.kcht.itsed.mws.subscribescheduler.facade.IPollManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class PollManager implements IPollManager{
	
	private Map<String,Object> ecSynLockMap = new HashMap<>();	//锁，用于同步poll结果
	private Map<String,ECReports> ecResultMap = new HashMap<>();	//用于暂存一个poll结果
	

	@Override
	public ECReports waitForECPollResult(String ecName) {
		synchronized(ecSynLockMap) {
			if(!ecSynLockMap.containsKey(ecName)) {
				ecSynLockMap.put(ecName, new Object());
			}
		}
		Object lock = ecSynLockMap.get(ecName);
		synchronized(lock) {
			try {
				ecResultMap.remove(ecName);
				lock.wait(10000);
			} catch (InterruptedException e) {
				log.error("",e);
			}
		}
		synchronized(ecResultMap) {
			return ecResultMap.get(ecName);
		}
	}

	@Override
	public void notifyECPollResult(String ecName, ECReports ecReports) {
		synchronized(ecResultMap) {
			ecResultMap.put(ecName, ecReports);
		}
		Object lock = ecSynLockMap.get(ecName);
		synchronized(lock) {
			lock.notifyAll();
		}
	}
}
